#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Created by master on 2017/3/11

import gevent

from gevent import socket, monkey

monkey.patch_all()  # 将阻塞的操作变成非阻塞


def server(port):
    s = socket.socket()
    s.bind(("0.0.0.0", port))
    s.listen(50)  # 最大监听数
    while True:
        cli, addr = s.accept()
        gevent.spawn(handle_request, cli)  # 启动一个新的协程


def handle_request(s):
    try:
        while True:
            data = s.recv(1024)
            print("recv:", data)
            s.send(data)
            if not data:
                s.shutdown(socket.SHUT_WR)
    except Exception as ex:
        print(ex)
    finally:
        s.close()


if __name__ == '__main__':
    server(8001)
